//
//  HTComposeView.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/25.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit
import pop
class HTComposeView: UIView {

    
    lazy var compButton : [HTComposeButton] = []
    lazy var array : [HTCompostModel] = {
    
        return self.composeInfo()
    }()
    
    var con : UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
    
        frame = UIScreen.mainScreen().bounds
//        backgroundColor = UIColor.blueColor()
        
        let image = getScreenShort().applyExtraLightEffect()
        
        let imageView = UIImageView(image: image)
        addSubview(imageView)
        
        addSubview(sloganImage)
        
        sloganImage.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            make.top.equalTo(100)
            
        }
        
        addMenButton()
//        let  data = UIImagePNGRepresentation(image)
//        
//        data?.writeToFile("/Users/jonson/1.png", atomically: true)
    }
    
    //添加菜单的按钮
    private func addMenButton(){
        
        let itemW : CGFloat = 80
        let itemH : CGFloat = 110
        let margin = (UIScreen.mainScreen().bounds.size.width - 3 * itemW) / 4
        
        let array = composeInfo()
        
        for (i ,value) in array.enumerate(){
        
            let button = HTComposeButton()
             button.addTarget(self, action: "didClickButton:", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = i
            button.setTitle(value.title, forState: .Normal)
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.frame.size = CGSize(width: itemW, height: itemH)
            button.setTitleColor(UIColor.blackColor(), forState: .Normal)
            addSubview(button)
            
            
           
            compButton .append(button)
            
            let col = i % 3
            let row = i / 3
            
            button.frame.origin.x = CGFloat(col) * itemW + CGFloat(col + 1) * margin
            button.frame.origin.y = CGFloat(row) * itemH + CGFloat(row) * 10 + UIScreen.mainScreen().bounds.size.height
            
            
            
        }
        
        
    }
    
    
    //显示弹出的控制器
    func show(conTarget: UIViewController){
    
        conTarget.view.addSubview(self)
        self.con = conTarget
    }
    
    //当移动到新的视图的时候调用
    override func didMoveToSuperview() {
        
        super.didMoveToSuperview()
        
        for(index,value) in compButton.enumerate(){
        
            animation(value, index: index, isUp: true)
        }
        
    }
    
    //pop动画
    private func animation(value: UIView, index: Int, isUp: Bool){

        
        let anim = POPSpringAnimation(propertyNamed:kPOPViewCenter )
        
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? -350 : 350)))
        
        anim.springSpeed = 10
        anim.springBounciness = 8
        
        anim.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        value.pop_addAnimation(anim, forKey: nil)
        
    }
    
    //点击按钮出动画
    @objc private func didClickButton(button : UIButton){
        
       UIView.animateWithDuration(0.25, animations: { () -> Void in
        
        for value in self.compButton{
            
            value.alpha = 0.01
            
            if value == button{
                
                value.transform = CGAffineTransformMakeScale(2, 2)
            }else{
                
                value.transform = CGAffineTransformMakeScale(0.01, 0.01)
            }
        }
        }) { (_) -> Void in
            
            UIView .animateWithDuration(0.25, animations: { () -> Void in
               
                let vc = HTCompostController()
                self.con?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()
                })
                
            })
        }
            
        
        
    
    }
    
    
    
    private func composeInfo() -> [HTCompostModel]{
    
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let  array = NSArray(contentsOfFile: path)!
        
        var tempArray : [HTCompostModel] = []
        
        for value in array{
        
            let info = HTCompostModel(dict: value as! [String : AnyObject])
            
            tempArray.append(info)

        }
        
        return tempArray
    
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        super.touchesBegan(touches, withEvent: event)
        for (index, value) in compButton.reverse().enumerate(){
        
            animation(value,index: index, isUp: false)
        }

        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
    }
    
    
    
    private func getScreenShort() ->UIImage{
    
        let  window = UIApplication.sharedApplication().keyWindow!
        
        let  rect = window.frame
        
        //开启上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 1)
        
        //渲染到上下文中
        window.drawViewHierarchyInRect(rect, afterScreenUpdates: true)
        
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }
    
    private lazy var sloganImage = UIImageView(image: UIImage(named: "compose_slogan"))

}
